using System;
using System.Collections.Generic;
using System.Linq;

namespace TXK
{
    /// <summary>
    /// Double类型转换库
    /// </summary>
    public class DoubleLib
    {
        /// <summary>
        /// 将字节数组中某8个字节转换成Double类型
        /// </summary>
        /// <param name="source">字节数组</param>
        /// <param name="start">开始位置</param>
        /// <param name="type">字节顺序</param>
        /// <returns>Double类型数值</returns>
        public static double GetDoubleFromByteArray(byte[] source, int start = 0, DataFormat type = DataFormat.ABCD)
        {
            byte[] array = ByteArrayLib.Get8ByteArray(source, start, type);
            return (array == null) ? 0.0 : BitConverter.ToDouble(array, 0);
        }

        /// <summary>
        /// 将字节数组转换成Double数组
        /// </summary>
        /// <param name="source">字节数组</param>
        /// <param name="type">字节顺序</param>
        /// <returns>Double数组</returns>
        public static double[] GetDoubleArrayFromByteArray(byte[] source, DataFormat type = DataFormat.ABCD)
        {
            double[] array = new double[source.Length / 8];
            for (int i = 0; i < source.Length / 8; i++)
            {
                array[i] = GetDoubleFromByteArray(source, 8 * i, type);
            }
            return array;
        }

        /// <summary>
        /// 将Double字符串转换成双精度浮点型数组
        /// </summary>
        /// <param name="val">Double字符串</param>
        /// <param name="spilt">Double字符串</param>
        /// <returns>双精度浮点型数组</returns>
        public static double[] GetDoubleArrayFromString(string val, char spilt = ' ')
        {
            val = val.Trim();
            List<double> list = new List<double>();
            if (val.Contains(spilt))
            {
                string[] array = val.Split(new char[1] { spilt }, StringSplitOptions.RemoveEmptyEntries);
                string[] array2 = array;
                foreach (string text in array2)
                {
                    list.Add(Convert.ToDouble(text.Trim()));
                }
            }
            else
            {
                list.Add(Convert.ToDouble(val.Trim()));
            }
            return list.ToArray();
        }
    }
}
